//
//  HMPlaceholderTextView.swift
//  HMWeibo12
//
//  Created by iOS on 16/9/26.
//  Copyright © 2016年 iOS. All rights reserved.
//

import UIKit

/// 带占位文本的textView
class HMPlaceholderTextView: UITextView {
    
    // 暴露属性给别人设置占位文本,不直接暴露label
    var placeholder: String? {
        didSet {
            placehodlerLabel.text = placeholder
        }
    }
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        // 添加子控件
        self.addSubview(placehodlerLabel)
        
        // 添加约束
        placehodlerLabel.translatesAutoresizingMaskIntoConstraints = false
        
        self.addConstraint(NSLayoutConstraint(item: placehodlerLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5))
        self.addConstraint(NSLayoutConstraint(item: placehodlerLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 8))
        
        // 注意: 代理只能设置一个,我们不能阻止外面的人使用
//        self.delegate = self
        // 使用通知,通知一对多
        // 注册通知
        // object: 通知的发送者, 填nil,任何对象发出的通知都能接受, 填了一个值就只能接受这个对象发出的通知
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: .UITextViewTextDidChange, object: self)
    }
    
    deinit {
        // 移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
    func textDidChange() -> Void {
        placehodlerLabel.isHidden = self.hasText
    }

    private lazy var placehodlerLabel: UILabel = {
        let label = UILabel()
        
        // 设置
        label.font = UIFont.systemFont(ofSize: 18)
        label.textColor = UIColor.lightGray
        label.text = "我是占位文本..."
        
        return label
    }()
}
//
//extension HMPlaceholderTextView: UITextViewDelegate {
//    func textViewDidChange(_ textView: UITextView) {
//        placehodlerLabel.isHidden = textView.hasText
//    }
//}
